package fosu.generated.controller;

import fosu.generated.common.Result;
import fosu.generated.common.ResultCode;
import fosu.generated.dto.DetectionResultDTO;
import fosu.generated.entity.Paper;
import fosu.generated.service.PaperService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 论文控制器
 */
@RestController
@RequestMapping("/paper")
@CrossOrigin(origins = "*")
public class PaperController {

    private static final Logger logger = LoggerFactory.getLogger(PaperController.class);

    @Autowired
    private PaperService paperService;

    /**
     * 上传论文
     */
    @PostMapping("/upload")
    public Result<Map<String, Object>> uploadPaper(
            @RequestParam("file") MultipartFile file,
            @RequestParam("userId") Long userId) {

        logger.info("上传论文请求，用户ID: {}, 文件名: {}", userId, file.getOriginalFilename());

        try {
            Paper paper = paperService.uploadPaper(file, userId);

            Map<String, Object> data = new HashMap<>();
            data.put("paperId", paper.getId());
            data.put("title", paper.getTitle());
            data.put("totalParagraphs", paper.getTotalParagraphs());

            logger.info("上传成功，论文ID: {}", paper.getId());
            return Result.success("上传成功", data);

        } catch (Exception e) {
            logger.error("上传失败", e);
            return Result.error(ResultCode.PAPER_UPLOAD_FAILED);
        }
    }

    /**
     * 检测论文
     */
    @PostMapping("/detect/{paperId}")
    public Result<DetectionResultDTO> detectPaper(@PathVariable Long paperId) {
        logger.info("检测论文请求，论文ID: {}", paperId);

        try {
            DetectionResultDTO result = paperService.detectPaper(paperId);
            logger.info("检测完成，论文ID: {}", paperId);
            return Result.success("检测完成", result);

        } catch (Exception e) {
            logger.error("检测失败", e);
            return Result.error(ResultCode.PAPER_DETECTION_FAILED);
        }
    }

    /**
     * 改写段落
     */
    @PostMapping("/rewrite")
    public Result<DetectionResultDTO> rewriteParagraph(@RequestBody Map<String, Object> request) {
        Long paperId = Long.valueOf(request.get("paperId").toString());
        Long paragraphId = Long.valueOf(request.get("paragraphId").toString());

        logger.info("改写段落请求，论文ID: {}, 段落ID: {}", paperId, paragraphId);

        try {
            DetectionResultDTO result = paperService.rewriteParagraph(paperId, paragraphId);
            logger.info("改写完成");
            return Result.success("改写完成", result);

        } catch (Exception e) {
            logger.error("改写失败", e);
            return Result.error(ResultCode.PAPER_REWRITE_FAILED);
        }
    }

    /**
     * 获取论文列表
     */
    @GetMapping("/list/{userId}")
    public Result<List<Paper>> getPaperList(@PathVariable Long userId) {
        logger.info("获取论文列表请求，用户ID: {}", userId);

        try {
            List<Paper> papers = paperService.getPaperList(userId);
            return Result.success(papers);

        } catch (Exception e) {
            logger.error("获取列表失败", e);
            return Result.error();
        }
    }

    /**
     * 导出报告
     */
    @GetMapping("/export/{paperId}")
    public Result<Void> exportReport(@PathVariable Long paperId) {
        logger.info("导出报告请求，论文ID: {}", paperId);

        try {
            paperService.exportReport(paperId);
            return Result.success("导出成功");

        } catch (Exception e) {
            logger.error("导出失败", e);
            return Result.error();
        }
    }

    /**
     * 删除论文
     */
    @DeleteMapping("/{paperId}")
    public Result<Void> deletePaper(@PathVariable Long paperId) {
        logger.info("删除论文请求，论文ID: {}", paperId);

        try {
            // TODO: 实现删除逻辑
            return Result.success("删除成功");

        } catch (Exception e) {
            logger.error("删除失败", e);
            return Result.error();
        }
    }
}